//
//  InTheSnowAppDelegate.m
//  InTheSnow
//networkActivityIndicatorVisible
//  Created by di on 7/23/09.
//  Copyright INTELLECTSOFT 2009. All rights reserved.
//
#import "Loader.h"
#import "TopBarView.h"
#import "BannersParser.h"
#import "UIBannerImageView.h"
#import "RotateButton.h"
#import "InTheSnowAppDelegate.h"
#import "NewssViewController.h"
#import <QuartzCore/CALayer.h>
#import "RSSParser.h"

#define local @"http://172.22.215.7/~di/rssInTheSnow.xml"

#define dateNews(i) [(News*)[rssContentEvents objectAtIndex:i] date]

#define DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) / 180.0 * M_PI)
@interface CALayer ()
- (void)setContents:(id)c;
@end

@interface InTheSnowAppDelegate ()
- (void)bubleSort_;
@property NSTimeInterval animationInterval;
@property (nonatomic, assign) NSTimer *animationTimer;

@end

@implementation InTheSnowAppDelegate

@synthesize rssContent;
@synthesize rssContentResorts; 
@synthesize rssContentGear;
@synthesize rssContentDeals;
@synthesize firstPageImage;
@synthesize tabBarController;
@synthesize isOffline;
@synthesize isFirst;
@synthesize topBar;
@synthesize toolBar;
@synthesize banners;
@synthesize toolBar;
@synthesize rssContentEvents;
@synthesize animationInterval;
@synthesize animationTimer;
@synthesize whole;
@synthesize dateUpdated;
@synthesize window;
@synthesize navigationController;

- (void)postReload
{
	[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:nil];	
}

- (void) addNews:(NSMutableArray*)n
{
	[self.rssContentEvents addObjectsFromArray:n];
//	NSLog([n description]);
 
}

- (void) initToolBar 
{
	toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 401, 320, 30)];  
    [toolBar.layer setContents:(id)[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"footer"		ofType:@"png" inDirectory:@"/"]].CGImage];
	[window addSubview:toolBar]; 
	[toolBar setTintColor:[UIColor clearColor]]; 
	[toolBar setHidden:YES];
	
	RotateButton *whole_ = [[RotateButton alloc] initWithFrame:CGRectMake(11, 5, 20, 20)];
	whole_.image = [UIImage imageNamed:@"loader.png"];
	[self setWhole:whole_];
	whole_.userInteractionEnabled = YES;
	[toolBar addSubview:whole_];
	[whole_ release];
	
	
	angle = 0;
	
	UILabel *toolTitle = [[UILabel alloc] initWithFrame:CGRectMake(40, 5, 150, 22)];
	[toolTitle setText:@"Last updated:"];
	[toolTitle setFont:[UIFont fontWithName:@"Helvetica" size:11]];
	[toolTitle setTextColor:[UIColor whiteColor]];
	[toolTitle setBackgroundColor:[UIColor clearColor]];
	[toolBar addSubview:toolTitle];
	[toolTitle release];
	
	UILabel *dateUpdated_ = [[UILabel alloc] initWithFrame:CGRectMake(110, 5, 200, 22)];
	[toolBar addSubview:dateUpdated_];
	[dateUpdated_ setTextColor:[UIColor whiteColor]];
	[dateUpdated_ setFont:[UIFont fontWithName:@"Helvetica" size:11]];
	[dateUpdated_ setBackgroundColor:[UIColor clearColor]];  
	self.dateUpdated = dateUpdated_;
	[dateUpdated_ release];
	
	TopBarView *topBar_ = [[TopBarView alloc] initWithFrame:CGRectMake(0, 20, 320, 44)];  
	[self.tabBarController.view  addSubview:topBar_];
	[self setTopBar:topBar_];
	[topBar_ release];	 
	
}

- (void)navigationController:(UINavigationController *)navigationControllerr willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{ 
//	[self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void) toolBarChange
{
//	toolBar.hidden = !toolBar.hidden;
}

#pragma mark -
#pragma mark Application lifecycle

- (void)applicationDidFinishLaunching:(UIApplication *)application 
{    
	
	[navigationController.navigationBar.layer setContents:(id)[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"header"ofType:@"png"inDirectory:@"/"]].CGImage]; 
	isFirst = YES;
    [window makeKeyAndVisible];
	
	[self initToolBar];
	
	self.animationInterval = 0.015;
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startAnimation) name:@"rotate" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stopAnimation) name:@"norotate" object:nil]; 
	
	NSMutableArray *rssContentNews_ = [[NSMutableArray alloc] init];
	self.rssContentEvents = rssContentNews_;
	[rssContentNews_ release];
	NSMutableArray *rssContentResorts_ = [[NSMutableArray alloc] init];
	self.rssContentResorts = rssContentResorts_;
	[rssContentResorts_ release];
	NSMutableArray *rssContentGear_ = [[NSMutableArray alloc] init];
	self.rssContentGear = rssContentGear_;
	[rssContentGear_ release];
	NSMutableArray *rssContentDeals_ = [[NSMutableArray alloc] init];
	self.rssContentDeals = rssContentDeals_;
	[rssContentDeals_ release];
	NSMutableArray *banners_ = [[NSMutableArray alloc] init];
	self.banners = banners_;
	[banners_ release];
	
	NSMutableArray *rssContent_ = [[NSMutableArray alloc] init];
	self.rssContent = rssContent_;
	[rssContent_ release];
	
	[self startAnimation];
	
	if(self.isOffline) return;
	BannersParser *banParser = [[BannersParser alloc] initWithUrl:[NSURL URLWithString:@"http://www.inthesnow.com/index.php?id=50"]];
	Loader *ldb = [[Loader alloc]initWithFeedType:1 parser:banParser];
	[ldb release]; 
	
 
}

- (void)afterFirstLoading
{
	[window addSubview:[tabBarController view]];	
//	[window addSubview:[navigationController view]];
	[self.firstPageImage setHidden:YES];
	[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application 
{
	NSLog(@"%i",[rssContentDeals count]);
	NSLog(@"%i",[rssContentEvents count]);
	NSLog(@"%i",[rssContentResorts count]);
	NSLog(@"%i",[rssContentGear count]);
	[rssContentEvents release];
}

- (void)rotate
{
	if (angle > 360) {
		angle = 5;
		if(isStop)
		{			
			self.animationTimer = nil;
			isStop = NO;
		}
	}
	
	[self.whole setTransform:CGAffineTransformMakeRotation(DEGREES_TO_RADIANS(angle))];
	angle += 5;
}

#pragma mark --
#pragma mark Timer

- (void)startAnimation 
{
    self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(rotate) userInfo:nil repeats:YES];
	if(!self.isOffline)
		dateUpdated.text = @"UPDATING...";
	[(NewssViewController*) navigationController.visibleViewController setToFirst:NO];
	RSSParser *parserr = [[RSSParser alloc] initWithUrl:[NSURL URLWithString:@"http://www.inthesnow.com/index.php?id=47"] dictIndex:kEvents];
	Loader *ldrss = [[Loader alloc]initWithFeedType:0 parser:parserr];
 
	[ldrss release];
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}

- (void)stopAnimation 
{
	if(!self.isOffline)
		dateUpdated.text = @"";
	isStop = YES;
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
	[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
	if(!self.isOffline)
		dateUpdated.text = [dateFormatter stringFromDate:[NSDate date]];
	[dateFormatter release];
	[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
	[self bubleSort_];
}

- (void)setAnimationTimer:(NSTimer *)newTimer 
{
    [animationTimer invalidate];
    animationTimer = newTimer;
}

- (void)setAnimationInterval:(NSTimeInterval)interval 
{
    
    animationInterval = interval;
    if (animationTimer) {
        [self stopAnimation];
        [self startAnimation];
    }
}

- (void)bubleSort_
{

	
	for (int i = [rssContentEvents count]-1; i > 0; i--) {
		for (int j = 0; j < i; j++) {
			if([dateNews(j) timeIntervalSinceReferenceDate]<[dateNews(j+1) timeIntervalSinceReferenceDate])
			{
				[rssContentEvents exchangeObjectAtIndex:j withObjectAtIndex:j+1];
			}
		}
	}
	
}

- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
	Class newsContrl3  = (NSClassFromString(@"NewssViewController")); 
	
	if(!([viewController class] == newsContrl3  ))	 
		[self.toolBar setHidden:YES];
	
	return YES;
}

#pragma mark -
#pragma mark Memory management

- (void)dealloc 
{

	[rssContent release];
	[rssContent release];
	[rssContentResorts release];
	[rssContentGear release];
	[rssContentDeals release];
	[firstPageImage release];
	[tabBarController release];
	[topBar release];
	[whole release];
	[banners release];
	[toolBar release];
	[toolBar release];
	[navigationController release];
	[window release];
	[super dealloc];
}

@end

